package com.test.rpc;

import com.test.rpc.codec.Decoder;
import com.test.rpc.codec.Encoder;
import com.test.rpc.common.ReflectionUtils;

import java.lang.reflect.Proxy;

public class RpcClient {
    private RpcClientConfig config;//配置
    private Encoder encoder;//序列化
    private Decoder decoder;//反序列化
    private TransportSelector selector;//选择器

    public RpcClient() {//无参构造方法
        this(new RpcClientConfig());
    }

    public RpcClient(RpcClientConfig config) {//基于配置的构造方法
        this.config = config;

        this.encoder = ReflectionUtils.newInstance(this.config.getEncoderClass());
        this.decoder = ReflectionUtils.newInstance(this.config.getDecoderClass());
        this.selector = ReflectionUtils.newInstance(this.config.getSelectorClass());

        this.selector.init(this.config.getServers(), this.config.getConnectCount(), this.config.getTransportClass());
    }

    //获取接口的代理对象
    public <T> T getProxy(Class clazz) {
        return (T) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{clazz}, new RemoteInvoker(clazz, encoder, decoder, selector));
    }
}
